import { login, getUser } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { mutations } from '@/store/mutations'

const state = {
  token: getToken(),
  name: '',
  roles: [],
  uinfo: {},
  isGetUser: false,
  accessPermissions: [],
  permissions: [],
  permissionsTree: []
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_ATTR', { key: 'token', data: data.token })
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getUser({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      getUser(state.token).then(response => {
        const { data } = response
        commit('SET_ATTR', { key: 'roles', data: data.roles })
        commit('SET_ATTR', { key: 'uinfo', data: data.uinfo })
        commit('SET_ATTR', { key: 'isGetUser', data: true })
        dispatch('GenerateTree', data.resoures)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  GenerateTree: function({ commit }, data) {
    return new Promise(resolve => {
      const menus = data
      commit('SET_ATTR', {
        key: 'permissions',
        data: JSON.parse(JSON.stringify(menus)) })
      function cmp(a, b) {
        return a.pid - b.pid
      }
      if (menus instanceof Array && menus.length > 0) {
        const s = new Set()
        menus.sort(cmp)
        const midObj = {}
        for (var i = menus.length - 1; i >= 0; i--) {
          const nowPid = menus[i].pid
          const nowId = menus[i].id
          s.add(menus[i].permission)
          // 建立当前节点的父节点的children 数组
          if (!midObj[nowPid]) midObj[nowPid] = []
          midObj[nowPid].push(menus[i])
          // 将children 放入合适的位置
          if (midObj[nowId]) {
            midObj[nowId].sort((a, b) => {
              return b.weight - a.weight
            })
            menus[i].children = midObj[nowId]
            delete midObj[nowId]
          }
        }
        commit('SET_ATTR', { key: 'permissionsTree', data: midObj[0]['0'] })
        commit('SET_ATTR', { key: 'accessPermissions', data: s })
        resolve()
      }
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      commit('SET_ATTR', { key: 'token', data: '' })
      commit('SET_ATTR', { key: 'roles', data: [] })
      commit('SET_ATTR', { key: 'isGetUser', data: false })
      removeToken()
      // resetRouter()
      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_ATTR', { key: 'token', data: '' })
      commit('SET_ATTR', { key: 'roles', data: [] })
      removeToken()
      resolve()
    })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
